package cn.edu.zut.hhr.service.impl;

import cn.edu.zut.hhr.entity.User;
import cn.edu.zut.hhr.service.LoginService;
import cn.edu.zut.hhr.service.UserService;
import cn.edu.zut.hhr.utils.JwtUtil;
import cn.edu.zut.hhr.utils.MD5Util;
import cn.edu.zut.hhr.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserService userService;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public String login(Long username, String password) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        password = MD5Util.encrypt(password);
        queryWrapper.eq(User::getId,username);
        queryWrapper.eq(User::getPassword,password);
        User user = userService.getOne(queryWrapper);
        if(user != null){
            Map<String,Object> map = new HashMap<>();
            map.put("username",username);
            String token = JwtUtil.createToken(map);
            redisUtil.setex("username_" + username, JSON.toJSONString(user),60*60*24);
            return token;
        }
        return null;
    }

    @Override
    public void logout(String token) {
        try{
            String username = JwtUtil.verifyToken(token).get("username").toString();
            redisUtil.del(username);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
